package com.bamboowind.dead.maxlen;

import com.bamboowind.util.RabbitMqUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author cpw
 * @Date 2022/11/2 8:57
 * 消费者C1
 */
public class Consumer01 {

    /**
     * 普通交换机，TTL过期的时候将消息传递给死信交换机
     */
    public static final String NORMAL_QUEUE = "normal-queue";

    /**
     * 死信队列，与死信交换机绑定，消费者C2
     */
    public static final String DEAD_QUEUE = "dead-queue";

    /**
     * 普通交换机，生产者发送消息过来传递给普通队列
     */
    public static final String NORMAL_EXCHANGE = "normal_exchange";


    /**
     * 死信交换机，接收普通交换机传递的信息和死信队列绑定
     */
    public static final String DEAD_EXCHANGE = "dead_exchange";

    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMqUtils.getChannel();
        // 声明普通交换机和死信交换机，类型为direct
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);

        // 声明死信队列
        channel.queueDeclare(DEAD_QUEUE, false, false, false, null);
        // 死信队列和死信交换机绑定,routingKey为lisi
        channel.queueBind(DEAD_QUEUE, DEAD_EXCHANGE, "lisi");


        // 正常队列过期后处理...
        Map<String, Object> arguments = new HashMap<>();
        // 正常队列设置死信交换机,key是固定值
        arguments.put("x-dead-letter-exchange", DEAD_EXCHANGE);
        // 正常队列设置死信routingKey,key是固定值
        arguments.put("x-dead-letter-routing-key", "lisi");
        // 正常队列的长度限制
        arguments.put("x-max-length", 6);

        // 普通队列和普通交换机绑定,routingKey为zhangsan
        channel.queueDeclare(NORMAL_QUEUE, false, false, false, arguments);
        channel.queueBind(NORMAL_QUEUE, NORMAL_EXCHANGE, "zhangsan");

        System.out.println("等待接收消息:");
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            System.out.println("C1消费者接收到的消息为:" + new String(message.getBody(), "UTF-8"));
            // 手动确认
            channel.basicAck(message.getEnvelope().getDeliveryTag(), false);
        };

        CancelCallback cancelCallback = (consumerTag) -> {
            System.out.println("C1消费者取消消费操作");
        };

        channel.basicConsume(NORMAL_QUEUE, false, deliverCallback, cancelCallback);
    }

}
